﻿using Lan.ServiceCore.IService;
using Lan.ServiceCore.Services;
using Lan.ServiceCore.TargetCollection;
using Model;

namespace Lan.ServiceCore.AlarmRecord
{
    public class AlarmRecordController
    {
        private readonly IAlarmService AlarmService;
        #region 定义

        //SpVoice voice = null; //语音

        //报警事件委托
        public delegate void InvokeAlarm();

        /// <summary>
        /// 当报警被创建时发生
        /// </summary>
        public event InvokeAlarm invokeAlarm; //事件

        public void OnInvokeAlarm()
        {
            if (invokeAlarm != null)
                invokeAlarm();
        }

        const int MAX_COMPUTE_COUNT = 4;

        List<int> threadIdList = new List<int>(MAX_COMPUTE_COUNT * 2);

        #endregion

        #region 单例

        //私有构造函数
        private AlarmRecordController(IAlarmService alarmService = null)
        {
            try
            {
                AlarmService = alarmService;
                //语音
                //voice = new SpVoice();

                //for (int i = 0; i < MAX_COMPUTE_COUNT * 2; i++)
                //{
                //    threadIdList.Add(i);
                //}
            }
            catch (Exception ex)
            {
                //Log.Error(ex.ToString());
            }
        }

        //单例实例
        private static AlarmRecordController instance = null;

        //同步锁
        private static readonly object syncRoot = new object();

        //获得单例实例
        public static AlarmRecordController GetInstance()
        {
            try
            {
                //双重锁定，保证线程安全和性能
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                        {
                            instance = new AlarmRecordController();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //Log.Error(ex.ToString());
            }
            return instance;
        }

        #endregion

        #region 报警处理线程
        //控制线程
        System.Threading.Thread thread;
        //线程运行状态
        bool threadRunning = false;

        //开启线程
        public bool ThreadStart()
        {
            try
            {
                threadRunning = true;
                thread = new System.Threading.Thread(ThreadRun);
                thread.IsBackground = true;
                thread.Name = "报警记录线程";
                thread.Start();
                //Log.Debug(thread.Name + "_已开启");
                return true;
            }
            catch (Exception ex)
            {
                //Log.Error(ex.ToString());
                return false;
            }
        }

        //等待线程结束
        public bool ThreadStop()
        {
            try
            {
                if (thread != null)
                {
                    //停知录像，关闭找个流和播放

                    threadRunning = false;
                    //停止线程
                    thread.Join();//等待线程停止
                    //Log.Debug(thread.Name + "_已停止");
                    thread = null;
                }

                return true;
            }
            catch (Exception ex)
            {
                //Log.Error(ex.ToString());
                return false;
            }
        }

        //控制线程
        void ThreadRun()
        {
            System.Threading.Thread.Sleep(1000);
            while (threadRunning)
            {
                try
                {
                    System.Threading.Thread.Sleep(100);

                    DateTime now = DateTime.Now;
                    //遍历所有防区
                    foreach (WDefenceArea defence in DefenceAreaManager.GetInstance())
                    {

                        if (defence.IsAlarmInHand && (defence.RadarAlarmOvertime() || defence.AlarmVideoOvertime(now)))
                        {
                            //清除防区报警状态
                            defence.Alarm = null;
                            defence.IsAlarmInHand = false;
                            continue;
                        }
                        //没有报警 自动结束一个报警
                        if (defence.Alarm == null)
                        {
                            defence.ClearLostTargets();
                            continue;
                        }

                        //防区是否报警处理状态 手动结束报警
                        if (!defence.IsAlarmInHand)
                        {
                            DealWithAlarm(defence); //新增报警报警记录

                        }


                    }

                }
                catch (Exception ex)
                {
                    //Log.Error(ex.ToString());
                }
            }
            //Log.Debug(thread.Name + "_运行结束");
        }


        #endregion

        //处理防区报警

        private bool DealWithAlarm(WDefenceArea defence)
        {
            try
            {
                if (defence == null)
                {
                    return false;
                }

                AlarmRecord ar = defence.Alarm;
                defence.AlarmBeginTime = ar.Time - TimeSpan.FromMilliseconds(500);
                Console.WriteLine("防区产生新的报警记录");
                defence.IsAlarmInHand = true;
                defence.ClearLostTargets();



                bool bl = false;
                //报警录像
                if (defence.Camera != null && defence.Camera.StartSaveFile(ar.VideoName, ar.Time, defence.Cameras))
                {
                    bl = true;

                }

                AlarmService alarmService = new AlarmService();

                string videoname = ar.VideoName.Find((item) => (item.Contains(ar.WCameraIp)));

                AlarmModel alarm = new AlarmModel() { AreaId = ar.AreaId, AreaName = ar.Name, DateTime = ar.Time, VideoName = videoname, CameraIp = ar.WCameraIp };
                alarmService.Add(alarm);


                return true;
            }
            catch (Exception ex)
            {
                defence.Alarm = null;
                defence.IsAlarmInHand = false;
                //Log.Error("DealWithAlarm:" + ex.ToString());
                return false;
            }
        }


        System.Threading.Thread thread2;
        public bool ThreadStart2()
        {
            try
            {
                threadRunning = true;
                thread2 = new System.Threading.Thread(ThreadRun2);
                thread2.IsBackground = true;
                thread2.Name = "清除线程";
                thread2.Start();
                return true;
            }
            catch (Exception ex)
            {
                //Log.Error(ex.ToString());
                return false;
            }
        }

        void ThreadRun2()
        {
            System.Threading.Thread.Sleep(50);
            while (true)
            {
                try
                {
                    System.Threading.Thread.Sleep(100);

                    DateTime now = DateTime.Now;
                    //遍历所有防区
                    foreach (WDefenceArea defence in DefenceAreaManager.GetInstance())
                    {
                        defence.CheckPathOvertimeAlarm();
                        defence.CheckPathOvertime();
                    }
                }
                catch (Exception ex)
                {
                    //Log.Error(ex.ToString());
                }
            }
        }


        System.Threading.Thread thread3;
        public bool ThreadStart3()
        {
            try
            {
                threadRunning = true;
                thread3 = new System.Threading.Thread(ThreadRun3);
                thread3.IsBackground = true;
                thread3.Name = "目标详细信息保存";
                thread3.Start();
                return true;
            }
            catch (Exception ex)
            {
                //Log.Error(ex.ToString());
                return false;
            }
        }
        AlarmService alarmService = new AlarmService();
        TrackService trackService = new TrackService();
        void ThreadRun3()
        {
            System.Threading.Thread.Sleep(50);
            while (true)
            {
                try
                {
                    System.Threading.Thread.Sleep(100);

                    DateTime now = DateTime.Now;
                    //遍历所有防区
                    foreach (WDefenceArea defence in DefenceAreaManager.GetInstance())
                    {
                        if (defence.IsAlarmInHand == true)
                        {
                            List<TargetPath> targetList = new List<TargetPath>();

                            foreach (var item in defence.TargetList)
                            {
                                targetList.Add(item);
                            }
               
                            foreach (var item in targetList)
                            {
                                TrackModel track = new TrackModel();
                                track.TargetId = item.TargetId;
                                track.AlarmID = alarmService.GatMaxAlarmId(defence.ID);
                                track.TargetId = item.TargetId;
                                track.AxesX = item.AxesX;
                                track.AxesY = item.AxesY;
                                track.AzimuthAngle = item.AzimuthAngle;
                                track.Distance = item.Distance;
                                track.UpdateTime = DateTime.Now;
                                trackService.AddTrack(track);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.Write(ex.ToString());
                }
            }
        }
    }
}
